package handler

import (
	"api/common/response"
	"api/internal/request"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	pb "order-server/proto"
)

func CartCreate(c *gin.Context) {
	json := request.CartCreateRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		response.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		zap.S().Error(err)
	}
	con := pb.NewOrderClient(client)
	req := &pb.CartCreateReq{
		GoodId: int64(json.GoodId),
		Number: int64(json.Number),
	}
	create, err := con.CartCreate(c, req)
	if err != nil {
		response.JsonRes(c, 400, err.Error(), nil)
		return
	}
	response.JsonRes(c, 200, "购物车添加成功", create)
}

func OrderCreate(c *gin.Context) {
	json := request.OrderCreateRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		response.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		zap.S().Error(err)
	}
	con := pb.NewOrderClient(client)
	req := &pb.OrderCreateReq{
		GoodId: int64(json.GoodId),
		Number: int64(json.Number),
	}
	create, err := con.OrderCreate(c, req)
	if err != nil {
		response.JsonRes(c, 400, err.Error(), nil)
		return
	}
	response.JsonRes(c, 200, "订单创建成功", create)
}

func OrderShow(c *gin.Context) {
	json := request.OrderShowRequest{}
	err := c.ShouldBindJSON(&json)
	if err != nil {
		response.JsonRes(c, 400, "请求参数错误", nil)
		return
	}
	client, err := grpc.NewClient("127.0.0.1:50051", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		zap.S().Error(err)
	}
	con := pb.NewOrderClient(client)
	req := &pb.OrderShowReq{
		Sn: json.Sn,
	}
	create, err := con.OrderShow(c, req)
	if err != nil {
		response.JsonRes(c, 400, err.Error(), nil)
		return
	}
	response.JsonRes(c, 200, "订单展示成功", create)
}
